<template>
  <div>
    <h1>留言板</h1>

    <el-table :data="messageBoardPage.records" style="width: 100%">
      <el-table-column prop="userName" label="用户名"></el-table-column>
      <el-table-column prop="content" label="留言内容"></el-table-column>
      <el-table-column prop="createdAt" label="留言时间"></el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="messageBoardPage.current"
        :page-size="messageBoardPage.size"
        :background="true"
        layout="total, prev, pager, next"
        :total="messageBoardPage.total"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-form
      :model="messageBoardForm"
      :rules="rules"
      ref="messageBoardFormRef"
      style="margin-top: 20px"
    >
      <el-form-item label="留言内容" prop="content">
        <el-input
          type="textarea"
          v-model="messageBoardForm.content"
          placeholder="请输入留言内容"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitMessage">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
// import
import { request } from '@/utils/request'
import { onBeforeMount, ref } from 'vue'
import { ElMessage } from 'element-plus'
// data
const messageBoardPage = ref({
  total: 0,
  size: 10,
  current: 1,
  records: [],
})
const messageBoardFormRef = ref(null)
const messageBoardForm = ref({
  content: '',
})
const rules = ref({
  content: [{ required: true, message: '留言内容不能为空', trigger: 'blur' }],
})
// 方法
const requestMessageBoardPage = async () => {
  try {
    let response = await request.get('/api/message-board/page', {
      params: {
        current: messageBoardPage.value.current,
      },
    })
    messageBoardPage.value = response
  } catch (error) {
    console.error(error)
    ElMessage.error('获取留言列表失败')
  }
}

const submitMessage = async () => {
  try {
    const valid = await messageBoardFormRef.value.validate((valid, fields) => {
      if (!valid) {
        console.error(fields)
      }
      return valid
    })
    if (!valid) {
      return
    }
    await request.post('/api/message-board/add/auth', messageBoardForm.value)
    messageBoardForm.value = {}
    await requestMessageBoardPage()
    ElMessage.success('留言提交成功')
  } catch (error) {
    console.error(error)
    ElMessage('提交留言时出错，请稍后重试')
  }
}

const handleCurrentChange = () => {
  requestMessageBoardPage()
}

onBeforeMount(() => {
  requestMessageBoardPage()
})
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
